<?php
/**
 * My new Zend Framework project
 * 
 * @author  
 * @version 
 */

require_once 'Zend/Controller/Plugin/Abstract.php';
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Request/Abstract.php';
require_once 'Zend/Controller/Action/HelperBroker.php';
require_once "Zend/Loader.php"; 
require_once 'Zend/Config.php';
require_once 'Zend/Config/Ini.php';
require_once 'Zend/Db.php';

/**
 * 
 * Initializes configuration depndeing on the type of environment 
 * (test, development, production, etc.)
 *  
 * This can be used to configure environment variables, databases, 
 * layouts, routers, helpers and more
 *   
 */
class Initializer extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Config
     */
    protected static $_config;

    /**
     * @var string Current environment
     */
    protected $_env;

    /**
     * @var Zend_Controller_Front
     */
    protected $_front;

    /**
     * @var string Path to application root
     */
    protected $_root;

    /**
     * @var Database connection variable
     */
    public static $_db;
        
    /**
     * @var string Path to application routes
     */
    protected static $_routes;
    
    /**
     * @var string Path to application root
     */    
    private static $_host     = null;
    
    /**
     * Constructor
     *
     * Initialize environment, root path, and configuration.
     * 
     * @param  string $env 
     * @param  string|null $root 
     * @return void
     */
    public function __construct($env, $root = null)
    {
        $this->_setEnv($env);
        if (null === $root) {
            $root = realpath(dirname(__FILE__) . '/../');
        }
        $this->_root = $root;
        
        $this->initPhpConfig();
        
        $this->_front = Zend_Controller_Front::getInstance();
        
        // set the test environment parameters
        if ($env == 'test') {
			// Enable all errors so we'll know when something goes wrong. 
			error_reporting(E_ALL | E_STRICT);  
			ini_set('display_startup_errors', 1);  
			ini_set('display_errors', 1); 

			$this->_front->throwExceptions(true);  
        }

		// Set up autoload.
		Zend_Loader::registerAutoload(); 
    }

    /**
     * Initialize environment
     * 
     * @param  string $env 
     * @return void
     */
    protected function _setEnv($env) 
    {
		$this->_env = $env;    	
    }
    

    /**
     * Initialize Data bases
     * 
     * @return void
     */
    public function initPhpConfig()
    {
        if (self::$_config != null) {
            return self::$_config;
        }

    	$host	= $_SERVER['HTTP_HOST'];
		
        try {
    		self::$_config = new Zend_Config_Ini(realpath(dirname(__FILE__) . '/../') . '/application/config/config.ini', $host, true);
        } catch (Zend_Config_Exception $e) {
        	die('Could not load config');
        }
        
    	return self::$_config;
    }
    
    /**
     * Get the URI Data bases
     * 
     * @return void
     */
	public static function getUri()
	{
		if (self::$_host != null) {
            return self::$_host;
		}
		
		Zend_Loader::loadClass('Zend_Uri');
		
		// self::$_host instanceof Zend_Uri_Http
		self::$_host = Zend_Uri::factory('http');
		
		// set the Uri as the current Uri
		self::$_host->setHost($_SERVER['SERVER_NAME']);
		
		return self::$_host;
	}
    
    /**
     * Route startup
     * 
     * @return void
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
       	$this->initDb();
        $this->initHelpers();
        $this->initView();
        $this->initPlugins();
        $this->initRoutes();
        $this->initControllers();
    }
    
    /**
     * Initialize data bases
     * 
     * @return void
     */
    static public function initDb()
    {
    	
    	if (self::$_db != null) {
    		return self::$_db;
    	}
   	
    	self::$_db = Zend_Db::factory(self::initPhpConfig()->db->adapter,
    								  array(
											'host'				=> self::initPhpConfig()->db->host,
							    		    'username'			=> self::initPhpConfig()->db->params->username,
							    	   	    'password'			=> self::initPhpConfig()->db->params->password,
							    		    'dbname'			=> self::initPhpConfig()->db->params->dbname,
    								  ));
    	Zend_Db_Table::setDefaultAdapter(self::$_db);
    	self::$_db->setFetchMode(Zend_Db::FETCH_OBJ);
		return self::$_db;    
    	
    	/*
    	mysql_connect(
    				self::initPhpConfig()->db->host,
    				self::initPhpConfig()->db->params->username,
    				self::initPhpConfig()->db->params->password);
		mysql_select_db(self::initPhpConfig()->db->params->dbname);
    	*/
    }

    /**
     * Initialize action helpers
     * 
     * @return void
     */
    public function initHelpers()
    {
    	// register the default action helpers
    	Zend_Controller_Action_HelperBroker::addPath($this->_root . self::initPhpConfig()->dir->helpers, 'Helper');
    }
    
    /**
     * Initialize view 
     * 
     * @return void
     */
    public function initView()
    {
		// Bootstrap layouts
		Zend_Layout::startMvc(array(
		    'layoutPath' => $this->_root .  self::initPhpConfig()->styles->layouts,
		    'layout' => 'main'
		));
    }
    
    /**
     * Initialize plugins 
     * 
     * @return void
     */
    public function initPlugins()
    {
    	
    }
    
    /**
     * Initialize routes
     * 
     * @return void
     */
    public function initRoutes()
    {
    	if (self::$_routes != null) {
            return self::$_routes;
		}

		self::$_routes = $this->_front->getRouter()->addConfig(new Zend_Config_Ini($this->_root . self::initPhpConfig()->files->routes));
			
		return self::$_routes;
    }

    /**
     * Initialize Controller paths 
     * 
     * @return void
     */
    public function initControllers()
    {
    	$this->_front->addControllerDirectory($this->_root . self::initPhpConfig()->path->controllers, 'default');
    }
    
	public static function generateToken($seed = '68sNnx6l')
	{
		$token = md5($seed.mktime());
		$globalSession = new Zend_Session_Namespace('global');
		$globalSession->token = $token;
		return $token;
	}
}
?>
